package com.yupi.springbootinit.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
*Excel 相关工具类
*/
public class ExcelUtils {

    public static String excelToCvs(MultipartFile multipartFile){
//        File file = null;
//        try {
//            file = ResourceUtils.getFile("C:/Users/席彭坤/Desktop/ll.xls");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        List<Map<Integer,String>> list = null;//同步读取,返回结果集
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLS)//设置读入类型
                    .sheet()//获取sheet构造器
                    .headRowNumber(0)//设置头行数,默认为1
                    .doReadSync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (list.size()==0){
            return "";
        }
        //转换为csv
        StringBuilder stringBuilder = new StringBuilder();
        //读取表头
        LinkedHashMap<Integer,String> headMap = (LinkedHashMap)list.get(0);
        System.out.println(headMap);
        List<String> collect = headMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
        stringBuilder.append(StringUtils.join(collect,',')).append("\n");
        System.out.println(stringBuilder);
        //读取数据
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer,String> dateMap = (LinkedHashMap)list.get(i);
            List<String> dataCollect = dateMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(dataCollect,',')).append("\n");
        }
        return stringBuilder.toString();
    }

}
